package com.wry.netty.server.chatroom;

import com.wry.netty.handler.MessageEncoder;
import com.wry.netty.handler.ServerMsgHandler;
import com.wry.netty.handler.ServerTransferMsgHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * <h1> 聊天服务端 <h1>
 *
 * @author wry
 * @since 2023/4/18 15:56
 */
public class ChatroomServerApp {

    public static void main(String[] args) {
        final NioEventLoopGroup boosLoopGroup = new NioEventLoopGroup();
        final NioEventLoopGroup workLoopGroup = new NioEventLoopGroup();

        try {
            final ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosLoopGroup, workLoopGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<>() {
                        @Override
                        protected void initChannel(Channel channel) throws Exception {
                            channel.pipeline().addLast(new MessageEncoder(),new ServerTransferMsgHandler(), new ServerMsgHandler());
                        }
                    })
                    .option(ChannelOption.SO_LINGER, 1024 * 10)
                    .childOption(ChannelOption.SO_KEEPALIVE, true);

            ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
            channelFuture.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            boosLoopGroup.shutdownGracefully();
            workLoopGroup.shutdownGracefully();
        }
    }
}
